<template>
    <div>
    	<div class="ui-flex" style="margin-bottom: 20px; padding: 20px; background-color: #ebebeb;">
    		<div class="ui-flex-full" style="line-height: 22px;">
    			<p>运费模板说明：如开启运费模板，则编辑商品时需设置使用哪一个运费模板计算运费，如关闭运费模板，默认使用订单运费模板，订单运费模板可编辑，但不可删除和关闭</p>
				<p>运费模板计费方式分为累加计算和组合计算，具体设置请到基本设置中购物设置选择计费方式，的具体计算方式请参考<a>《运费模板计费说明》</a></p>
    		</div>
    		<div style="padding-left: 20px;">
    			<iSwitch size="large" :true-value="1" :false-value="0">
					<span slot="open">开启</span>
					<span slot="close">关闭</span>
				</iSwitch>
    		</div>
    	</div>
    	<div class="ivu-table-wrapper">
            <div class="ivu-table">
                <table style="width: 100%;" cellspacing="0" cellpadding="0" border="0">
                	<colgroup>
	    				<col width="260" />
	    				<col />
	    				<col width="280" />
	    			</colgroup>
                    <thead>
                        <tr>
                            <th colspan="2">
                                <div class="ivu-table-cell">订单运费模板</div>
                            </th>
                            <th style="text-align: right;">
                                <div class="ivu-table-cell">订单运费模板仅在运费模板关闭时自动启用</div>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <div class="ivu-table-cell">订单统一运费({{ currency }})：{{ freightMoneys.fee }}</div>
                            </td>
                            <td>
                                <div class="ivu-table-cell">订单免运费金额({{ currency }})：{{ freightMoneys.free }}</div>
                            </td>
                            <td style="text-align: right;">
                                <div class="ivu-table-cell">
                                    <Button @click="handleShowConfigModal" size="small" type="primary">配置</Button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
        <div style="margin: 20px -20px; height: 1px; background-color: #ebebeb;"></div>
        
        <Button type="primary" @click="handleJumpEdit()">新建运费模板</Button>
        
    	<div>
    		<div v-for="(item, index) in datas" :key="index" class="ivu-table-wrapper" style="margin-top: 20px;">
		    	<div class="ivu-table">
		    		<table style="width: 100%;" cellspacing="0" cellpadding="0" border="0">
		    			<colgroup>
		    				<col width="240" />
		    				<col width="240" />
		    				<col />
		    				<col width="190" />
		    			</colgroup>
			            <thead>
			                <tr>
			                    <th colspan="3">
			                        <div class="ivu-table-cell">{{ item.name }}</div>
			                    </th>
			                    <th style="text-align: right;">
			                        <div class="ivu-table-cell">{{item.type == 'weight' ? '按重量计算' : '按件数计算'}}</div>
			                    </th>
			                </tr>
			            </thead>
			            <tbody>
			                <tr>
			                    <td>
			                        <div class="ivu-table-cell">
			                        	<a href="javascript:;">查看可配送区域</a>
			                        </div>
			                    </td>
			                    <td>
			                        <div class="ivu-table-cell">{{ handleGetFirst(item) }}</div>
			                    </td>
			                    <td>
			                        <div class="ivu-table-cell">{{ handleGetSecond(item) }}</div>
			                    </td>
			                    <td style="text-align: right;">
			                        <div class="ivu-table-cell">
			                        	<iSwitch :value="item.enabled" size="large" :true-value="1" :false-value="0" @on-change="handleChangeEnabled(item)">
											<span slot="open">启用</span>
											<span slot="close">关闭</span>
										</iSwitch>
										<Button type="primary" size="small" @click="handleJumpEdit({id: item.id})" style="margin: 0 5px;">配置</Button>
										<Poptip title="确定要删除吗？" placement="left" confirm transfer @on-ok="handleDelete(item.id)">
											<Button type="error" size="small">删除</Button>
										</Poptip>
			                        </div>
			                    </td>
			                </tr>
			                <tr>
			                	<td colspan="4" class="ivu-table-expanded-cell">
			                		<div class="ivu-table-cell">123</div>
			                	</td>
			                </tr>
			            </tbody>
			        </table>
				</div>
			</div>
    	</div>
    	
        <DrawerForm
        	title="订单运费模板配置"
        	v-model="showConfigModal"
        	ok-text="保存"
        	:mask-closable="false"
        	@on-ok="handleSubmitConfig"
        >
        	<Form label-position="top">
                <FormItem label="订单统一运费:">
                    <InputAmount v-model="formData.fee" placeholder="设置订单运费统一价格"></InputAmount>
                </FormItem>
                <FormItem label="订单免运费金额：">
                    <InputAmount v-model="formData.free" placeholder="设置免运费金额"></InputAmount>
                </FormItem>
            </Form>
        </DrawerForm>
        
    </div>
</template>
<script>
import Util from '@/libs/util.js';
import InputAmount from '@/components/form/InputAmount.vue';
import DrawerForm from '@/components/DrawerForm.vue';
export default {
    components: {
        InputAmount,
        DrawerForm
    },
    computed: {
        currency () {
            return this.$store.state.config.currency;
        },
        deliveryTemplates() {
        	return this.$store.state.app.deliveryTemplates;
        }
    },
    data() {
        return {
            showConfigModal: false, //订单运费模板显示绑定
            freightMoneys: {
            	fee : 0,
                free: 0,
            },
            formData : {
                fee : 0,
                free: 0,
            },
            datas: []
        }
    },
    mounted() {
    	// 获取运费模板
    	this.$store.dispatch('getDeliveryTemplates');
    	
    	this.init();
    },
    watch: {
    	deliveryTemplates: {
    		deep: true,
    		handler(val) {
    			this.init();
    		}
    	}
    },
    methods: {
    	init() {
    		let templates = this.deliveryTemplates;
    		if(!templates || templates.length == 0) return false;
    		this.datas = templates.filter(item => {
				if(item.id == 1) {
					this.freightMoneys.fee = Number(item.delivery_info.fee);
					this.freightMoneys.free = Number(item.delivery_info.free);
					return false;
				}
				return true;
			})
    	},
    	// 首重
    	handleGetFirst(item) {
    		let unit = item.type == 'weight' ? 'KG' : '件';
        	let title = item.type == 'weight' ? '首重' : '首件';
        	if(!item.delivery_info || item.delivery_info.length == 0) {
        		return h('span', title + '：');
        	}
        	if(!item.delivery_info[0]) {
        		return h('span', title + '：');
        	}
        	let temp = item.delivery_info[0].template;
            return title + '：' + temp.first_fee +'/'+ temp.first_value +'（'+ unit +'）';
    	},
    	// 续重
    	handleGetSecond(item) {
    		let unit = item.type == 'weight' ? 'KG' : '件';
        	let title = item.type == 'weight' ? '续重' : '续件';
        	if(!item.delivery_info || item.delivery_info.length == 0) {
        		return h('span', title + '：');
        	}
        	if(!item.delivery_info[0]) {
        		return h('span', title + '：');
        	}
        	let temp = item.delivery_info[0].template;
            return title + '：' + temp.follow_fee +'/'+ temp.follow_value +'（'+ unit +'）';
    	},
    	handleShowConfigModal() {
    		this.formData.fee = this.freightMoneys.fee;
    		this.formData.free = this.freightMoneys.free;
    		this.showConfigModal = true;
    	},
        handleJumpEdit(query) {
            this.$router.push({name: 'setup_freight_config', query});
        },
        // 开关
        handleChangeEnabled(row) {
        	let status = row.enabled == 1 ? 0 : 1;
        	Util.ajax.post(this.API['API_SETTING_DELIVERY_TEMPLATES_ENABLED'], {id: row.id, status, status}).then(res => {
        		this.$Message.success('操作成功');
        		let templates = this.deliveryTemplates.map(item => {
        			if(item.id == id) {
        				item.enabled = status;
        			}
        			return item;
        		})
        		this.$store.commit('setDeliveryTemplates', templates);
        	}).catch(() => {
        		
        	})
        },
        handleDelete(id) {
        	if(id <= 1) {
        		this.$Message.error('统一模板不能删除');
        		return false;
        	}
        	Util.ajax.post(this.API['API_SETTING_DELIVERY_TEMPLATES_DESTROY'], {id: id}).then(res => {
        		this.$Message.success('删除成功');
        		let templates = this.deliveryTemplates.filter(item => {
        			return item.id != id;
        		})
        		this.$store.commit('setDeliveryTemplates', templates);
        	}).catch(() => {
        		
        	})
        },
        // 保存配置
        handleSubmitConfig() {
        	let params = {
        		id: 1,
        		name: '统一运费模板',
        		type: 'unification',
        		data: this.formData
        	}
        	Util.ajax.post(this.API['API_SETTING_DELIVERY_TEMPLATES_SAVE'], params).then(res => {
        		this.$Message.success('配置修改成功');
        		this.showConfigModal = false;
        		this.freightMoneys.fee = this.formData.fee;
        		this.freightMoneys.free = this.formData.free;
        	}).catch(() => {
        		
        	})
        }
    }
}
</script>